package com.budwk.app.sqfwDoc.codeGeneratorV2.pdfService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.StrFormatter;
import cn.hutool.json.JSONUtil;
import com.budwk.app.sqfw.models.*;
import com.budwk.app.sqfw.services.*;
import com.budwk.app.sqfw.services.datamange.DataMangeCommunityService;
import com.budwk.app.sqfwDoc.codeGenerator.pdfGenerate.AbstractCustomerPdfCreateField;
import com.budwk.app.sqfwDoc.codeGeneratorV2.capacity.AbstractCreatePdfCapacity;
import com.budwk.app.sqfwDoc.codeGeneratorV2.capacity.IAfterCreatePdfCapacity;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.BusinessParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.CommonParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.PdfGenerateParam;
import com.budwk.app.sqfwDoc.codeGeneratorV2.fileParam.Sqfw2PdfGPForController;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.BasePdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.generate.ResultOfPdfGenerator;
import com.budwk.app.sqfwDoc.codeGeneratorV2.result.GeneratorPdfWordResult;
import com.budwk.app.sys.models.Sys_unit;
import com.budwk.app.sys.models.Sys_user;
import com.budwk.app.sys.services.SysUnitService;
import com.budwk.app.sys.services.SysUserService;
import com.budwk.app.util.ThreadPoolExecutorUtil;
import com.budwk.app.util.poiUtils.CommonPdfAndWordResult;
import com.budwk.app.util.poiUtils.nutzBeanUtils.NutzIocUtils;
import com.google.common.collect.Maps;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.nutz.ioc.loader.annotation.Inject;
import org.nutz.trans.Trans;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author ZY.Wang
 * @since 2024/6/6
 * <p>
 * 这是一个没有什么必要存在的类
 */
@Slf4j
public abstract class Sqfw2PdfService extends AbstractCreatePdfCapacity implements IAfterCreatePdfCapacity {

    public static final String forSummaryNewConsName = "formSummaryNew";
    public static final String completeFlowConsName = "completeFlow";
    public static final String userIdConsName = "userId";

    ExecutorService executorService = Executors.newFixedThreadPool(20);

    @Inject
    protected SqfwFormsummaryNewService sqfwFormsummaryNewService;
    @Inject
    protected SysUserService sysUserService;
    @Inject
    private DataMangeCommunityService dataMangeCommunityService;

    public Map<String, Object> createPdfAndMsg(Sqfw2PdfGPForController paramForController) {
        Map<String, Object> businessMap = saveBusinessData(paramForController);
        Sqfw_formSummary_new formSummary = (Sqfw_formSummary_new) businessMap.get(forSummaryNewConsName);

        executorService.execute(() -> {

            getBusinessData(formSummary);

            // 初始化一下生成结果
            GeneratorPdfWordResult generateResult = new GeneratorPdfWordResult();

            try {
                PdfGenerateParam pdfGenerateParam = createPdfParam(formSummary, businessMap);
                pdfGenerateParam.setPdfCreateConfigList(paramForController.getPdfCreateConfigList());
                generateResult = super.generatePdf(pdfGenerateParam);
            } catch (Exception e) {
                log.error("pdf create error,will update data status...");
            }

            generateResult.getBridgeMap().putAll(businessMap);
            generateResult.setReCreatePdfFlag(false);
            afterGeneratePdf(generateResult);
        });
        return businessMap;
    }

    protected void getBusinessData(Sqfw_formSummary_new formSummary) {

    }

    public void reCreatePdfAndMsg(Sqfw2PdfGPForController paramForController) {
        Sqfw_formSummary_new formSummary = paramForController.getFormSummary();

        Map<String, Object> businessDataMap = Maps.newHashMap();

        beforeReGenPdf(formSummary, businessDataMap);

        executorService.execute(() -> {
            PdfGenerateParam pdfGenerateParam = createPdfParam(formSummary, businessDataMap);
            GeneratorPdfWordResult generateResult = super.generatePdf(pdfGenerateParam);

            // 设置需要向下传递的数据
            Map<String, Object> bridgeMap = generateResult.getBridgeMap();
            if (bridgeMap == null) {
                bridgeMap = Maps.newHashMap();
            }
            bridgeMap.put("formSummaryNew", formSummary);
            bridgeMap.put("userId", formSummary.getCreateBy());
            generateResult.setBridgeMap(bridgeMap);

            generateResult.setReCreatePdfFlag(true);

            afterGeneratePdf(generateResult);
        });
    }

    public PdfGenerateParam createPdfParam(Sqfw_formSummary_new formSummary, Map<String, Object> businessDataMap) {
        PdfGenerateParam pdfGenerateParam = new PdfGenerateParam();

        BusinessParam businessParam = new BusinessParam();
        businessParam.setFillDate(formSummary.getFillDate());
        pdfGenerateParam.setBusinessParam(businessParam);

        pdfGenerateParam.setAbstractCustomerPdfCreateField(getCustomerPdfField(formSummary.getParamData()));

        CommonParam commonParam = getCreateUserPdfParam(formSummary.getCreateBy());

        pdfGenerateParam.setCreateUserCommonParam(commonParam);

        customerPopularPdfGenerateParam(pdfGenerateParam, businessDataMap);

        return pdfGenerateParam;
    }

    public Map<String, Object> saveBusinessData(Sqfw2PdfGPForController paraForController) {
        String userId = paraForController.getUserId();
        SqfwServicerecordService sqfwServicerecordService = NutzIocUtils.getBean(SqfwServicerecordService.class);
        SysUnitService sysUnitService = NutzIocUtils.getBean(SysUnitService.class);
        SqfwWorkorderService sqfwWorkorderService = NutzIocUtils.getBean(SqfwWorkorderService.class);
        SqfwCompleteflowService sqfwCompleteflowService = NutzIocUtils.getBean(SqfwCompleteflowService.class);

        Sys_user sysUser = sysUserService.fetch(userId);
        Sys_unit unit = sysUnitService.fetch(sysUser.getUnitId());

        Map<String, Object> callBackMap = Maps.newHashMap();

        Sqfw_formSummary_new formSummary = paraForController.getFormSummary();
        List<String> ids = new ArrayList<String>();
        Trans.exec(() -> {
            Sqfw_servicerecord serviceRecord = new Sqfw_servicerecord();
            serviceRecord.setCustomer_name(sysUser.getUsername());
            serviceRecord.setCustomer_phone(sysUser.getLoginname());
            serviceRecord.setType("养老服务巡查");
            serviceRecord.setCustomer_need(StrFormatter.format("养老服务巡查【{}】", DateUtil.format(new Date(), "MM-dd")));
            serviceRecord.setService_name(sysUser.getUsername());
            serviceRecord.setService_phone(sysUser.getLoginname());
            serviceRecord.setCreatedBy(sysUser.getId());
            serviceRecord.setCreatedAt(new Date().getTime());
            serviceRecord.setUpdatedBy(sysUser.getId());
            serviceRecord.setUpdatedAt(new Date().getTime());
            serviceRecord.setDelFlag(true);
            serviceRecord.setConnect_time(new Date());
            serviceRecord.setUser_id(sysUser.getId());
            serviceRecord.setFinishStatus("new");
            serviceRecord.setCompanyName(unit.getName());
            serviceRecord.setProvince(sysUser.getProvince());
            serviceRecord.setCity(sysUser.getCity());
            serviceRecord.setDistrict(sysUser.getDistrict());
            serviceRecord.setCounty(sysUser.getCounty());
            sqfwServicerecordService.insert(serviceRecord);

            // 然后保存workOrder
            Sqfw_workorder workOrder = new Sqfw_workorder();
            workOrder.setSqfw_id(serviceRecord.getId());
            workOrder.setUser_name(sysUser.getUsername());
            workOrder.setWk_status("new");
            workOrder.setWk_grade("0");
            workOrder.setWk_priority("take_time_complete");
            workOrder.setCreatedBy(sysUser.getId());
            workOrder.setCreateDate(new Date());
            workOrder.setUpdatedBy(sysUser.getId());
            workOrder.setUpdatedAt(new Date());
            workOrder.setDelflag(true);
            workOrder.setUser_id(sysUser.getId());
            workOrder.setFromUserId(sysUser.getId());
            workOrder.setToUserId(sysUser.getId());
            workOrder.setServiceType("养老服务巡查");
            sqfwWorkorderService.insert(workOrder);

            // 然后保存一张工作流的数据
            Sqfw_completeflow completeFlow = new Sqfw_completeflow();
            completeFlow.setSqfwId(serviceRecord.getId());
            completeFlow.setWorkerId(workOrder.getId());
            completeFlow.setFileType("养老服务巡查");
            completeFlow.setCreateDate(new Date());
            completeFlow.setPhone(sysUser.getLoginname());
            completeFlow.setUserId(sysUser.getId());
            completeFlow.setUserName(sysUser.getUsername());
            completeFlow.setResourcePath("creating");
            sqfwCompleteflowService.insert(completeFlow);

            formSummary.setCreateBy(userId);
            formSummary.setCreateDate(new Date());
            formSummary.setUpdateDate(new Date());
            formSummary.setUnitId(unit.getId());
            formSummary.setUnitName(unit.getName());
            Sys_user user = sysUserService.fetch(userId);
            formSummary.setCreateUserPhone(user.getLoginname());
            formSummary.setUpdateUserPhone(user.getLoginname());
            formSummary.setCreateUserName(user.getUsername());
            formSummary.setUpdateUserName(user.getUsername());
            formSummary.setSqfwId(serviceRecord.getId());
            formSummary.setSqfwFlowId(completeFlow.getId());
            formSummary.setWorkOrderId(workOrder.getId());
            beforeInsertForSummary(formSummary);
            sqfwFormsummaryNewService.insert(formSummary);
            afterInsertForSummary(formSummary);

            callBackMap.put(forSummaryNewConsName, formSummary);
            callBackMap.put(completeFlowConsName, completeFlow);

            popularBusinessDataMapAfterSaveBusinessData(callBackMap, paraForController);
            ids.add(formSummary.getId());
        });
        // 异步解析入数据管理模块
        try {
            ExecutorService executorService = ThreadPoolExecutorUtil.getInstance();
            CompletableFuture.runAsync(() -> {
                dataMangeCommunityService.cleanDataBySummaryId(ids);
            }, executorService);
        } catch (Exception ex) {
            log.error("clean data service error! id : {}", JSONUtil.toJsonStr(ids));
        }
        return callBackMap;
    }

    protected void popularBusinessDataMapAfterSaveBusinessData(Map<String, Object> callBackMap, Sqfw2PdfGPForController paraForController) {

    }


    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam) {

    }

    @Override
    protected void customerPopularPdfGenerateParam(PdfGenerateParam pdfGenerateParam, Map<String, Object> customerBusinessDataMap) {

    }

    @Override
    protected abstract List<BasePdfGenerator> getPdfGenerator(PdfGenerateParam pdfGenerateParam);

    @Override
    protected abstract String getDownloadFileName(PdfGenerateParam pdfGenerateParam);

    @Override
    protected void popularPdfGenerateResultBridgeMap(GeneratorPdfWordResult result, List<ResultOfPdfGenerator> pdfResultList) {

    }

    @Override
    protected abstract AbstractCustomerPdfCreateField getCustomerPdfField(String jasonStr);

    @Override
    public void afterGeneratePdf(GeneratorPdfWordResult generateResult) {
        Map<String, Object> bridgeMap = generateResult.getBridgeMap();
        Sqfw_formSummary_new formSummaryNew = (Sqfw_formSummary_new) bridgeMap.get(forSummaryNewConsName);
        Sqfw_completeflow completeFlow = (Sqfw_completeflow) bridgeMap.get(completeFlowConsName);
        String userId = (String) bridgeMap.get(userIdConsName);

        CommonPdfAndWordResult pdfAndWordResult = generateResult.getPdfAndWordResult();

        SqfwFormSummaryPdfService pdfService = NutzIocUtils.getBean(SqfwFormSummaryPdfService.class);
        SqfwCompleteflowService completeFlowService = NutzIocUtils.getBean(SqfwCompleteflowService.class);

        Sqfw_form_summary_pdf summaryPdf = new Sqfw_form_summary_pdf();
        summaryPdf.setSummaryId(formSummaryNew.getId());
        summaryPdf.setIndex(0); // 暂时认为0就是合集
        summaryPdf.setCreateDate(new Date());
        summaryPdf.setCreateBy(userId);
        summaryPdf.setUpdateBy(userId);

        String pdfUrl = pdfAndWordResult.getPdfUrl();
        if (StringUtils.isBlank(pdfUrl)) {
            log.info("pdf create error,will update status");
            summaryPdf.setStatus("3");

            completeFlow.setResourcePath("error");
        } else {
            log.info("pdf create success,will update status");
            summaryPdf.setUrl(pdfAndWordResult.getPdfUrl());
            summaryPdf.setStatus("1");

            completeFlow.setResourcePath(pdfAndWordResult.getPdfUrl());
        }

        pdfService.insert(summaryPdf);
        completeFlowService.update(completeFlow);
    }

    protected void beforeInsertForSummary(Sqfw_formSummary_new formSummary) {

    }

    protected void afterInsertForSummary(Sqfw_formSummary_new formSummary) {

    }

    protected void beforeReGenPdf(Sqfw_formSummary_new sqfwFormSummary, Map<String, Object> businessDataMap) {

    }

    //-----------------------------------------------------------------------------
    //  一些可以重写的方法
    //-----------------------------------------------------------------------------

    /**
     * 根据用户id创建通用参数
     *
     * @param createBy 用户id
     * @return 结果
     */
    protected CommonParam getCreateUserPdfParam(String createBy) {
        CommonParam commonParam = new CommonParam();
        SysUserService sysUserService = NutzIocUtils.getBean(SysUserService.class);
        Sys_user createUser = sysUserService.fetch(createBy);
        commonParam.setCreateUserId(createUser.getId());
        commonParam.setCreateUserName(createUser.getUsername());
        commonParam.setCreateUserPhone(createUser.getLoginname());
        commonParam.setUnitId(createUser.getUnitId());
        commonParam.setLevelCityUnitName(createUser.getUnitName());
        commonParam.setProvince(createUser.getProvince());
        commonParam.setCity(createUser.getCity());
        commonParam.setDistrict(createUser.getDistrict());
        commonParam.setCounty(createUser.getCounty());
        commonParam.setCommunity(createUser.getCommunity());
        commonParam.setCreateUserSigUrl(createUser.getSignatureUrl());

        SysUnitService sysUnitService = NutzIocUtils.getBean(SysUnitService.class);
        Sys_unit userUnit = sysUnitService.fetch(createUser.getUnitId());
        commonParam.setUnitName(userUnit.getName());
        return commonParam;
    }

    protected void getPdfGenerateResultAfter(ResultOfPdfGenerator pdfResult, BasePdfGenerator generator) {

    }

}
